package com.zl.learning.webservice.client;

import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.junit.Test;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.rpc.ServiceException;
import java.rmi.RemoteException;

public class CxfClient {
    public static void main(String[] args) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://127.0.0.1:81/helloWorld?wsdl");
        Object[] objects = null;
        String method = "say";
        try {
            objects = client.invoke(method, "aaa");
            System.out.println(objects[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String serviceCall(String url, String method, Object... args) {
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient(url);
        Object[] objects = null;
        try {
            objects = client.invoke(method, args);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return objects[0].toString();
    }

    private String serviceCall2(String namespace, String url, String method, String jsonArg, String generalArgument) {
        String value = null;
        try {
            Service service = new Service();
            Call call = (Call) service.createCall();
            call.setTargetEndpointAddress(url);
            call.setOperationName(new QName(namespace, method));
            call.addParameter("jsonArg", XMLType.XSD_STRING, ParameterMode.IN);
            call.addParameter("generalArgument", XMLType.XSD_STRING, ParameterMode.IN);
            call.setReturnType(XMLType.XSD_STRING);
            value = (String) call.invoke(new Object[]{jsonArg, generalArgument});
        } catch (ServiceException | RemoteException e) {
            e.printStackTrace();
        }
        return value;
    }

    @Test
    public void test1() {
        String wsdl = "http://localhost:8081/cxf/services/TestService?wsdl";
        String value = serviceCall(wsdl, "findUser");
        System.out.println(value);
    }

    @Test
    public void test2() {
        String wsdl = "http://localhost:8080/ws/spring/hello?wsdl";
        String val = serviceCall(wsdl, "sayHi", "zhangsan");
        System.out.println(val);
    }
}
